﻿using System;
using System.IO;
using System.Text;
using NUnit.Framework;
using System.Threading;

namespace Neoseeker.NAMFox.Tests
{
    public class TestBase
    {
        public static NAMFoxSelenium Selenium
        {
            get;
            set;
        }

        protected void RunQUnitTest(string testFile)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\" + testFile);
            var file = new FileInfo(path);

            if (!file.Exists)
            {
                throw new ArgumentException("The test file could not be found.", "testFile");
            }

            var testUrl = @"chrome://namfox/content/tests/unit-test-runner.html?script=file:///" + file.FullName;
            Console.WriteLine(testUrl);
            Selenium.Open(testUrl);

            Thread.Sleep(500);
            Selenium.WaitForCondition("selenium.browserbot.getCurrentWindow().document.getElementById('qunit-banner').className", "30000");
            
            if (Selenium.GetXpathCount("//ol[@id='qunit-tests']/li") == 0)
            {
                Assert.Fail("No tests ran.");
            }

            StringBuilder errors = new StringBuilder();
            var moduleCount = 1;

            string failedModuleXpathBase = "//ol[@id='qunit-tests']/li[@class='fail']";
            string failedModuleXpath = failedModuleXpathBase + "[" + moduleCount + "]";

            while (Selenium.IsElementPresent(failedModuleXpath))
            {
                errors.AppendLine(Selenium.GetText(failedModuleXpath + "/strong"));
                errors.AppendLine("------------------------------------------------------");
                var testCaseCount = 1;

                string failedTestCaseXpathBase = failedModuleXpath + "/ol/li[@class='fail']";
                string failedTestCaseXpath = failedTestCaseXpathBase + "[" + testCaseCount + "]";

                while (Selenium.IsElementPresent(failedTestCaseXpath))
                {
                    errors.AppendLine("    " + Selenium.GetText(failedTestCaseXpath));
                    failedTestCaseXpath = failedTestCaseXpathBase + "[" + (++testCaseCount) + "]";
                }

                errors.AppendLine();

                failedModuleXpath = failedModuleXpathBase + "[" + (++moduleCount) + "]";
            }

            var results = errors.ToString();
            if (results.Length > 0)
            {
                results += "\nRepro with URL: " + testUrl;
                Assert.Fail(results);
            }
        }
    }
}
